package de.hauck.rtmidlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import de.hauck.rtmidlet.model.Configuration;
import de.hauck.rtmidlet.model.IBBean;
import de.hauck.rtmidlet.model.IBQueryBean;
import de.hauck.rtmidlet.utils.MyLogger;
import de.hauck.rtmidlet.utils.Utils;
import de.hauck.rtmidlet.views.CanvasIB;

public class DownloadIBThread implements Runnable {
	private String _url;
	private CanvasIB _cIB;
	private String _code;
	private String _newUrl;
	private String _query;
	

	// private String
	// url2="https://www.interactivebrokers.com/Universal/servlet/FlexStatementService.GetStatement?q=<REFERENCE_CODE>&t=<TOKEN>&v=<SERVICE_VERSION>";

	public DownloadIBThread(CanvasIB cIB, String url, String query) {
		_cIB = cIB;
		_url = url;
		_query=query;
		new Thread(this).start();
	}

	public void run() {
		getCodeAndUrl();
		//getValues(_newUrl);
		if (Utils.isNumeric(_code)) {
			if (null != _newUrl) {
				_newUrl = _newUrl + "?q=" + _code + "&t="
						+ Configuration.IB_TOKEN + "&v=2";
				System.out.println(_newUrl);
				getValues(_newUrl);
			} else
				System.out.println("no url was found for download");
		} else
			_cIB.setText(_code);

	}

	private String getCodeAndUrl() {
		String newCode = "";
		InputStream is = null;
		try {
			_cIB.setText("Getting code & url for query "
					+ _query);
			System.out.println(_url);
			HttpConnection hc = (HttpConnection) Connector.open(_url);
			if (hc != null) {
				is = hc.openInputStream();
				_cIB.updateStatus(Configuration.CONN_STATUS_CONNECTING);
				int ch; // Check the Content-Length first
				long length = hc.getLength();
				String IBString = "";
				if (length != -1) {
					Configuration.addToDownloadCounter(length);
					_cIB.updateStatus(Configuration.CONN_STATUS_CONNECTED);
					for (int i = 0; i < length; i++)
						if ((ch = is.read()) != -1)
							IBString += ((char) ch);
				} else {
					// if the content-length is not available
					_cIB.updateStatus(Configuration.CONN_STATUS_CONNECTED);
					while ((ch = is.read()) != -1)
						IBString += ((char) ch);

				}
				is.close();
				hc.close();
				_cIB.isDownloading = false;
				_cIB.updateStatus(Configuration.CONN_STATUS_OFFLINE);
				System.out.println(IBString);
				int start = IBString.indexOf("<code>");
				int end = IBString.indexOf("</code>");
				newCode = IBString.substring(start + 6, end);
				System.out.println(newCode);

				_code = newCode;
				start = IBString.indexOf("<url>");
				end = IBString.indexOf("</url>");
				_newUrl = IBString.substring(start + 5, end);
				System.out.println(_newUrl);
				_cIB.setText("Code: " + newCode);

			}
		} catch (IOException e) {
			e.printStackTrace();
			_cIB.isDownloading = false;
			RTMidlet.getInstance().setCurrent(_cIB);
			RTMidlet.getInstance().alert("Error", e.getMessage(),
					Configuration.ALERT_WAIT_TIME);
		} catch (Exception e) {
			e.printStackTrace();
			_cIB.isDownloading = false;
			// RTMidlet.getInstance().setCurrent(_cIB);
			RTMidlet.getInstance().alert("Error", e.getMessage(),
					Configuration.ALERT_WAIT_TIME);
		}
		return newCode;

	}

	private String getValues(String newUrl) {
		_cIB.isDownloading=true;
		InputStream is = null;
		try {
			_cIB.setText("Getting Flex for code " + _code);
			HttpConnection hc = (HttpConnection) Connector.open(newUrl);
			if (hc != null) {
				is = hc.openInputStream();
				_cIB.updateStatus(Configuration.CONN_STATUS_CONNECTING);
				int ch; // Check the Content-Length first
				long length = hc.getLength();
				String IBString = "";
				if (length != -1) {
					Configuration.addToDownloadCounter(length);
					_cIB.updateStatus(Configuration.CONN_STATUS_CONNECTED);
					for (int i = 0; i < length; i++)
						if ((ch = is.read()) != -1)
							IBString += ((char) ch);
				} else {
					// if the content-length is not available
					_cIB.updateStatus(Configuration.CONN_STATUS_CONNECTED);
					while ((ch = is.read()) != -1)
						IBString += ((char) ch);

				}
				is.close();
				hc.close();
				
//				IBString =
//					"2010-06-09, 01:45:00|SELL|-6184|1.1927|7375.6568\n"+
//					"2010-06-09, 02:25:37|SELL|-6173|1.1956267|7380.603590413\n"+
//					"2010-06-09, 06:34:10|SELL|-6168|1.1986|7392.9648\n"+
//					"2010-06-09, 08:00:12|SELL|-6182|1.2000086|7418.453155632\n"+
//					"2010-06-09, 08:09:25|BUY|6184|1.20038477|-7423.179405567\n"+
//					"2010-06-09, 08:15:00|BUY|6181|1.201|-7423.381\n"+
//					"2010-06-09, 08:15:10|BUY|6186|1.20097423|-7429.22656701\n"+
//					"2010-06-09, 09:25:43|BUY|6173|1.20357861|-7429.690733924\n"+
//					"2010-06-09, 11:03:14|BUY|6168|1.2063|-7440.4584\n"+
//					"2010-06-09, 13:40:28|SELL|-6186|1.201|7429.386\n"+
//					"2010-06-09, 16:00:36|SELL|-868|1.1983|1040.1244\n"+
//					"2010-06-09, 01:45:00|SELL|-6184|1.1927|7375.6568\n"+
//					"2010-06-09, 02:25:37|SELL|-6173|1.1956267|7380.603590413\n"+
//					"2010-06-09, 06:34:10|SELL|-6168|1.1986|7392.9648\n"+
//					"2010-06-09, 08:00:12|SELL|-6182|1.2000086|7418.453155632\n"+
//					"2010-06-09, 08:09:25|BUY|6184|1.20038477|-7423.179405567\n"+
//					"2010-06-09, 08:15:00|BUY|6181|1.201|-7423.381\n"+
//					"2010-06-09, 08:15:10|BUY|6186|1.20097423|-7429.22656701\n"+
//					"2010-06-09, 09:25:43|BUY|6173|1.20357861|-7429.690733924\n"+
//					"2010-06-09, 11:03:14|BUY|6168|1.2063|-7440.4584\n"+
//					"2010-06-09, 13:40:28|SELL|-6186|1.201|7429.386\n"+
//					"2010-06-09, 16:00:36|SELL|-868|1.1983|1040.1244";
				
				System.out.println(IBString);
				_cIB.updateStatus(Configuration.CONN_STATUS_OFFLINE);
				if (IBString.indexOf("attention") > 0) {
					System.out.println("No trades reported yet");
					_cIB.setText("No trades reported yet");
				} else {
					_cIB.setIBQueryBean(convert2QueryBean(IBString));
				}
				_cIB.isDownloading=false;
			}
		} catch (IOException e) {
			e.printStackTrace();
			_cIB.isDownloading = false;
			RTMidlet.getInstance().setCurrent(_cIB);
			RTMidlet.getInstance().alert("Error", e.getMessage(),
					Configuration.ALERT_WAIT_TIME);
		} catch (Exception e) {
			e.printStackTrace();
			_cIB.isDownloading = false;
			// RTMidlet.getInstance().setCurrent(_cIB);
			RTMidlet.getInstance().alert("Error", e.getMessage(),
					Configuration.ALERT_WAIT_TIME);
		}
		return newUrl;
	}

		
	private IBQueryBean convert2QueryBean(String str) {
		IBBean ib = new IBBean();		
		Vector sellBeans = new Vector();
		Vector buyBeans = new Vector();
		double totalBuyAmount=0;
		double totalSellAmount=0;
		int totalBuyQuantity=0;
		int totalSellQuantity=0;
	
		int offset = 0;
		int counter = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == '|') {
				String token = str.substring(offset, i).replace('"', ' ')
						.trim();
				ib.setToken(counter, token);
				System.out.println("Setting "+counter+": "+token);
				counter++;
				offset = i + 1;
			} else if (str.charAt(i) == '\n' || i==str.length()-1) {
				String token = str.substring(offset, i - 1).replace('"', ' ')
						.trim();
				ib.setToken(counter, token);
				System.out.println("Setting last "+counter+": "+token);
				if (null!=ib && null!=ib.getBuySell() && ib.getBuySell().startsWith("SELL")) {
					sellBeans.addElement(ib);
					totalSellAmount+=ib.getAmount();
					totalSellQuantity+=ib.getQuantity();
				} else if (null!=ib && null!=ib.getBuySell() && ib.getBuySell().startsWith("BUY")) {
					buyBeans.addElement(ib);
					totalBuyAmount+=ib.getAmount();
					totalBuyQuantity+=ib.getQuantity();
				} else {
					System.out.println("unknown bean type");
				}
				counter = 0;
				offset = i + 1;
				ib.printBean();
				ib = new IBBean();
			}
			
		}
		MyLogger.debug("IB converted - size buy: " + buyBeans.size()+", sell: "+sellBeans.size());
		IBQueryBean ibQueryBean = new IBQueryBean(sellBeans,buyBeans,totalBuyAmount,totalSellAmount,totalBuyQuantity,totalSellQuantity);
		System.out.println("totals buy:  "+totalBuyAmount+" "+totalBuyQuantity);
		System.out.println("totals sell: "+totalSellAmount+" "+totalSellQuantity);
		ibQueryBean.setBuyPrice(totalBuyAmount/totalBuyQuantity);
		ibQueryBean.setSellPrice(totalSellAmount/totalSellQuantity);
		System.out.println("avg. buy:  "+(totalBuyAmount/totalBuyQuantity));
		System.out.println("avg. sell: "+(totalSellAmount/totalSellQuantity));
		return ibQueryBean;
	}
}
